package edu.gyc.myshop.service.impl;

import edu.gyc.myshop.model.Cart;
import edu.gyc.myshop.dao.CartDao;
import edu.gyc.myshop.model.Goods;
import edu.gyc.myshop.model.Myuser;
import edu.gyc.myshop.service.CartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.gyc.myshop.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ls
 * @since 2024-02-05
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartDao, Cart> implements CartService {


    @Autowired
    GoodsService goodsService;

    @Override

    public boolean putCart(Goods goods, HttpSession session) {
        Myuser user = (Myuser) session.getAttribute("user");
        if (user != null) {
            int uid = user.getId();
            int gid = goods.getId();
            Cart cart = this.lambdaQuery()
                    .eq(Cart::getGoodsId, gid)
                    .eq(Cart::getMyuserId,uid)
                    .one();
            if (cart != null) {

                this.lambdaUpdate()
                        .eq(Cart::getGoodsId, gid)
                        .set(Cart::getShoppingnum, cart.getShoppingnum() + goods.getBuyNum())
                        .update();
            } else {
                Cart tempCart = new Cart();
                tempCart.setGoodsId(gid);
                tempCart.setShoppingnum(goods.getBuyNum());
                tempCart.setMyuserId(uid);
                this.save(tempCart);
            }

            return true;
        }

        return false;
    }


    @Override
    public List<Cart> listCart(HttpSession session) {
        Myuser user = (Myuser) session.getAttribute("user");
        if (user != null) {
            int uid = user.getId();
            List<Cart> carts = this.lambdaQuery()
                    .eq(Cart::getMyuserId, uid)
                    .list();
            if (carts.size() > 0) {
                for (int i = 0; i < carts.size(); i++) {
                    Cart cart = carts.get(i);
                    Goods goods = goodsService.lambdaQuery()
                            .eq(Goods::getId, cart.getGoodsId()).one();
                    cart.setPriceSum(cart.getShoppingnum() * goods.getPrice());
                    cart.setGoodsPic(goods.getPicture());
                    cart.setGoodsPrice(goods.getPrice());
                    cart.setGoodsName(goods.getName());
                }
                return carts;

            }
        }

        return null;
    }
}
